import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const service = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 5000,
  withCredentials: true
  
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const access_token = localStorage.getItem('access_token')
    const refresh_token = localStorage.getItem('refresh_token')
    if (refresh_token) {
      config.headers['Authorization'] = `${access_token}`
      config.headers['x-refresh-token'] = `${refresh_token}`
    }
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    config.headers['Accept'] = 'application/json'

    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(res);
    
    // 这里可以根据后端的响应结构进行相应的处理
    if (res.code === 200) {
      if (res.data && res.data.access_token) {
        localStorage.setItem('access_token', res.data.access_token)
      }
      if (response.headers['x-refresh-token']) {
        localStorage.setItem('refresh_token', response.headers['x-refresh-token'])
      }
      return res
    } else if (res.code === 401) {
      setTimeout(() => {
        window.location.href = '/'
      }, 1500);
      
      return Promise.reject(new Error(res.message || '登录过期'))
    }
    else {
      ElMessage.error(res.msg || '请求失败')
      return Promise.reject(new Error(res.msg || '请求失败'))
    }
  }
)

// 封装请求方法
export const http = {
  get(url, params) {
    return service.get(url, { params })
  },
  post(url, data) {
    return service.post(url, data)
  },
  put(url, data) {
    return service.put(url, data)
  },
  delete(url, params) {
    return service.delete(url, { params })
  }
}

export default service